package com.ruoyi.hanyun.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.hanyun.domain.HyProjects;
import com.ruoyi.hanyun.mapper.HyProjectsMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.hanyun.service.IHyProjectsService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import javax.validation.Validator;

/**
 * 项目Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-27
 */
@Service
public class HyProjectsServiceImpl implements IHyProjectsService {
    @Autowired
    private HyProjectsMapper hyProjectsMapper;

    private static final Logger log = LoggerFactory.getLogger(HyProjectsServiceImpl.class);

    @Autowired
    protected Validator validator;
    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 查询项目
     *
     * @param id 项目主键
     * @return 项目
     */
    @Override
    public HyProjects selectHyProjectsById(Long id) {
        return hyProjectsMapper.selectHyProjectsById(id);
    }

    /**
     * 查询项目列表
     *
     * @param hyProjects 项目
     * @return 项目
     */
    @Override
    public List<HyProjects> selectHyProjectsList(HyProjects hyProjects) {
        return hyProjectsMapper.selectHyProjectsList(hyProjects);
    }

    /**
     * 新增项目
     *
     * @param hyProjects 项目
     * @return 结果
     */
    @Override
    public int insertHyProjects(HyProjects hyProjects) {
        return hyProjectsMapper.insertHyProjects(hyProjects);
    }

    /**
     * 修改项目
     *
     * @param hyProjects 项目
     * @return 结果
     */
    @Override
    public int updateHyProjects(HyProjects hyProjects) {
        return hyProjectsMapper.updateHyProjects(hyProjects);
    }

    /**
     * 批量删除项目
     *
     * @param ids 需要删除的项目主键
     * @return 结果
     */
    @Override
    public int deleteHyProjectsByIds(Long[] ids) {
        return hyProjectsMapper.deleteHyProjectsByIds(ids);
    }

    /**
     * 删除项目信息
     *
     * @param id 项目主键
     * @return 结果
     */
    @Override
    public int deleteHyProjectsById(Long id) {
        return hyProjectsMapper.deleteHyProjectsById(id);
    }

    //    导入任务信息
    @Override
    public String importProjects(List<HyProjects> projectsList, String operName) {
        if (StringUtils.isNull(projectsList) || projectsList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        List<SysUser> users = sysUserMapper.selectUserAllByStatus();

        Map<String, Long> ownerNameToIdMap = new HashMap<String, Long>();
        for (SysUser user : users) {
            ownerNameToIdMap.put(user.getUserName(), user.getUserId());
        }
        List<HyProjects> projectList = new ArrayList<HyProjects>();
        for (HyProjects projects : projectsList) {
            try {
                // 验证是否存在这个项目i
                Long ownerId = ownerNameToIdMap.get(projects.getOwnerName());
                if (StringUtils.isNull(ownerId)) {
                    throw new IllegalArgumentException("负责人名称无效或未找到");
                } else {
                    projects.setOwnerId(ownerId);
                }
                BeanValidators.validateWithException(validator, projects);
                projectList.add(projects);
                successNum++;
                if (projectList.size() > 10000) {
                    hyProjectsMapper.insertHyProjectsBatch(projectList);
                    projectList = new ArrayList<HyProjects>();
                }
//                successMsg.append("<br/>" + successNum + "、项目 " + projects.getName() + " 导入成功");

            } catch (Exception e) {
                projectList = new ArrayList<HyProjects>();
                failureNum++;
                String msg = "<br/>" + failureNum + "、项目 " + projects.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg);
                log.error(e + "");
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
